package net.mikoo.seals.biz.manager;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.gson.WeChat;
import com.gson.bean.TemplateData;

import net.mikoo.seals.biz.mapper.PersonMapper;
import net.mikoo.seals.biz.mapper.UserLoginMapper;
import net.mikoo.seals.biz.mapper.WechatMapper;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.common.enums.ApplyTypeEnum;
import net.mikoo.seals.model.Apply;
import net.mikoo.seals.model.ApplyVerify;
import net.mikoo.seals.model.Person;
import net.mikoo.seals.model.Seal;
import net.mikoo.seals.model.UserLogin;
import net.mikoo.seals.model.WechatUser;
import net.mikoo.seals.utils.DateUtil;

@Component
public class WechatManager {
	
	private Logger logger = LoggerFactory.getLogger(WechatManager.class);
	
	@Autowired
	private UserLoginMapper userLoginMapper;
	
	@Autowired
	private PersonMapper	personMapper;
	
	@Autowired
	private WechatMapper	wechatMapper;
	
	
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	
	/**
	 * 审核通过
	 * 
	 * 113Ud-pRHsJGU8BzIHwhVKccMRJwNNuFvTWiHnzIKSc
		
		审核通过通知
		{{first.DATA}}
		审核信息：{{keyword1.DATA}}
		审核人：{{keyword2.DATA}}
		审核时间：{{keyword3.DATA}}
		{{remark.DATA}}
	 * 
	 * 
	 */
	public void pass(Apply apply,Seal seal,ApplyVerify verify) {
		
		try {
			
			UserLogin userLogin = userLoginMapper.selectByPartyId(apply.getPartyId());
			
			if(userLogin == null) {
				throw new NullPointerException("userLogin not exist");
			}
			if(StringUtils.isBlank(userLogin.getUnionId())) {
				throw new NullPointerException("UnionId is null");
			}
			
			WechatUser wechatUser = wechatMapper.selectUserInfoByUnionId(userLogin.getUnionId());
			if(wechatUser == null) {
				throw new NullPointerException("wechatUser not exist");
			}
			
			String openid = wechatUser.getOpenid();
			if(StringUtils.isBlank(openid)) {
				throw new NullPointerException("openid is null");
			}
			
			Person person = personMapper.selectByPartyId(verify.getPartyId());
			
			String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
			TemplateData data = new TemplateData(openid, "9C0fyQBRFVby1gUA6W6F82gbfDVwV1GuB395RKSoT7o", null,"wx686d9ffcb83af55e","pages/myapply/details/details?applyId="+apply.getApplyId()+"&companyId="+apply.getCompanyId());
			data.push("first", "您申请的".concat(seal.getSealName()).concat(ApplyTypeEnum.getByCode(apply.getApplyType()).getMessage()).concat("审核通过"));
			data.push("keyword1", "审核通过");
			data.push("keyword2", person.getName());
			data.push("keyword3", DateUtil.formate(apply.getApplyTime(), "yyyy年MM月dd日 HH:mm:ss"));
			data.push("remark", "点击前往查看");
			WeChat.message.templateSend(accessToken, data);
			
			
			
			//同时推送给保管员
			
			
		}catch (Exception e) {
			logger.error("发送微信消息失败",e);
		}
		
		reserve(apply,seal,verify);
	}
	
	/**
	 * 审核拒绝
	 * w01xRNOi51pvcwQZ3qdlTwErVo52Bdrm63Q9LS563Mo
	 * {{first.DATA}}
		审核结果：{{keyword1.DATA}}
		原因选项：{{keyword2.DATA}}
		结束时间：{{keyword3.DATA}}
		{{remark.DATA}}
	 */
	public void reject(Apply apply,Seal seal,ApplyVerify verify) {
		
		try {
			
			UserLogin userLogin = userLoginMapper.selectByPartyId(apply.getPartyId());
			
			if(userLogin == null) {
				throw new NullPointerException("userLogin not exist");
			}
			if(StringUtils.isBlank(userLogin.getUnionId())) {
				throw new NullPointerException("UnionId is null");
			}
			
			WechatUser wechatUser = wechatMapper.selectUserInfoByUnionId(userLogin.getUnionId());
			if(wechatUser == null) {
				throw new NullPointerException("wechatUser not exist");
			}
			
			String openid = wechatUser.getOpenid();
			if(StringUtils.isBlank(openid)) {
				throw new NullPointerException("openid is null");
			}
			
			//Person person = personMapper.selectByPartyId(verify.getPartyId());
			
			String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
			TemplateData data = new TemplateData(openid, "_5UOgAZalAcH5bRkHnBRu7IOW3sdPtos9bugxCHFO9M", null,"wx686d9ffcb83af55e","pages/myapply/details/details?applyId="+apply.getApplyId()+"&companyId="+apply.getCompanyId());
			data.push("first", "您申请的".concat(seal.getSealName()).concat(ApplyTypeEnum.getByCode(apply.getApplyType()).getMessage()).concat("未审核通过"));
			data.push("keyword1", "未通过");
			data.push("keyword2", verify.getVerifyResult());
			data.push("keyword3", DateUtil.formate(verify.getVerifyTime(), "yyyy-MM-dd HH:mm:ss"));
			data.push("remark", "感谢您的使用");
			WeChat.message.templateSend(accessToken, data);
			
		}catch (Exception e) {
			logger.error("发送微信消息失败",e);
		}
		
	}

	/**
	 * 待审核
	 * 
	 * 
	 * 2I740YORTvU_gR6NLnaMYkRkmtVGs685XEN2hJbhrak
{{first.DATA}}
申请类型：{{keyword1.DATA}}
申请人姓名：{{keyword2.DATA}}
申请人电话：{{keyword3.DATA}}
申请时间：{{keyword4.DATA}}
申请内容：{{keyword5.DATA}}
{{remark.DATA}}
	 */
	public void await(Apply apply,Seal seal,ApplyVerify verify) {
		
		
		try {
			
			UserLogin userLogin = userLoginMapper.selectByPartyId(verify.getPartyId());
			
			if(userLogin == null) {
				throw new NullPointerException("userLogin not exist");
			}
			if(StringUtils.isBlank(userLogin.getUnionId())) {
				throw new NullPointerException("UnionId is null");
			}
			
			WechatUser wechatUser = wechatMapper.selectUserInfoByUnionId(userLogin.getUnionId());
			if(wechatUser == null) {
				throw new NullPointerException("wechatUser not exist");
			}
			
			String openid = wechatUser.getOpenid();
			if(StringUtils.isBlank(openid)) {
				throw new NullPointerException("openid is null");
			}
			
			
			Person person = personMapper.selectByPartyId(apply.getPartyId());
			
			String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
			TemplateData data = new TemplateData(openid, "EvVg4cwcjOds0FDLYQqxuYpA_ZmLe-EvqMhM23xAhI8", null,"wx686d9ffcb83af55e","pages/task/verify/verify?verifyId="+verify.getApplyVerifyId()+"&type=USE_APPLY&companyId="+apply.getCompanyId());
			data.push("first", "您有待审核的任务，请尽快处理");
			data.push("keyword1", ApplyTypeEnum.getByCode(apply.getApplyType()).getMessage());//申请类型
			data.push("keyword2", person.getName());//申请人姓名
			data.push("keyword3", person.getMobile());//申请人电话
			data.push("keyword4", DateUtil.formate(apply.getApplyTime(), "yyyy-MM-dd HH:mm:ss"));//申请时间
			data.push("keyword5", apply.getCause());//申请内容
			
			data.push("remark", "感谢您的支持，祝您生活愉快。");
			JSONObject result = WeChat.message.templateSend(accessToken, data);
			logger.info("sendresult"+result.toString());
		}catch (Exception e) {
			logger.error("发送微信消息失败",e);
		}
	}
	
	/**
	 * 异常
	 * 
	 *  {{first.DATA}}
	 *  异常类型：{{keyword1.DATA}}
	 *	时间：{{keyword2.DATA}}
	 *	{{remark.DATA}}
	 * 
	 * @param apply
	 * @param seal
	 * @param verify
	 */
	public void aberrant(String sealName, String typeName, long partyId) {
		try {
			
			UserLogin userLogin = userLoginMapper.selectByPartyId(partyId);
			if(userLogin == null) {
				throw new NullPointerException("userLogin not exist");
			}
			if(StringUtils.isBlank(userLogin.getUnionId())) {
				throw new NullPointerException("UnionId is null");
			}
			
			WechatUser wechatUser = wechatMapper.selectUserInfoByUnionId(userLogin.getUnionId());
			if(wechatUser == null) {
				throw new NullPointerException("wechatUser not exist");
			}
			
			String openid = wechatUser.getOpenid();
			if(StringUtils.isBlank(openid)) {
				throw new NullPointerException("openid is null");
			}
			Person person = personMapper.selectByPartyId(partyId);
			String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
			TemplateData data = new TemplateData(openid, "XsyhHUpgqFQSgzAGPgYtPLAYHOPrtCMhjf-SFHUBnK8");
			data.push("first", person.getName() + "使用印章【" + sealName + "】" + typeName);
			data.push("keyword1", "印章使用" + typeName);//异常类型
			data.push("keyword2", DateUtil.formate(new Date(), "yyyy-MM-dd HH:mm:ss"));//异常时间
			data.push("remark", "请联系管理员查看详细信息。");
			JSONObject result = WeChat.message.templateSend(accessToken, data);
			logger.info("sendresult"+result.toString());
		}catch (Exception e) {
			logger.error("发送微信消息失败",e);
		}
	}
	
	
	
	/**
	 * 预约审核通知
	 * 
	 * uPnzVQHDqYF_pz-2PaGsSvcXf4yXrquql6lMnlofH5M

	 * {{first.DATA}}
		申请内容：{{keyword1.DATA}}
		预约时间：{{keyword2.DATA}}
		申请人：{{keyword3.DATA}}
		申请时间：{{keyword4.DATA}}
		{{remark.DATA}}
	 * 
	 * 
	 * 
	 * @param apply
	 * @param seal
	 * @param verify
	 */
	public void reserve(Apply apply,Seal seal,ApplyVerify verify) {
		
		
		try {
			
			UserLogin userLogin = userLoginMapper.selectByPartyId(seal.getPartyId());
			
			if(userLogin == null) {
				throw new NullPointerException("userLogin not exist");
			}
			if(StringUtils.isBlank(userLogin.getUnionId())) {
				throw new NullPointerException("UnionId is null");
			}
			
			WechatUser wechatUser = wechatMapper.selectUserInfoByUnionId(userLogin.getUnionId());
			if(wechatUser == null) {
				throw new NullPointerException("wechatUser not exist");
			}
			
			String openid = wechatUser.getOpenid();
			if(StringUtils.isBlank(openid)) {
				throw new NullPointerException("openid is null");
			}
			
			Person person = personMapper.selectByPartyId(apply.getPartyId());
						
			String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
			TemplateData data = new TemplateData(openid, "_R-L4_7kyb-Dswb1FQdCt0u0pXPzwCbUaGTye0qFrTU");
			data.push("first", "有新的印章申请预约提醒");
			data.push("keyword1", seal.getSealName());//申请内容
			data.push("keyword2", DateUtil.formate(apply.getApplyTime(), "yyyy-MM-dd HH:mm:ss"));//预约时间
			data.push("keyword3", person.getName());//申请人
			data.push("keyword4", DateUtil.formate(apply.getApplyTime(), "yyyy-MM-dd HH:mm:ss"));//申请时间
			data.push("remark", "请等待或联系及处理");
			JSONObject result = WeChat.message.templateSend(accessToken, data);
			logger.info("sendresult"+result.toString());
		}catch (Exception e) {
			logger.error("发送微信消息失败",e);
		}
	}
	
	
	
	
	
}
